<script setup>
import { ref, watch, nextTick } from 'vue'
import { useChatStream } from '../hooks/useChatStream.js'

const messages = ref([])
const input = ref('')
const chatContainer = ref()
const { streamChat, isStreaming, error, abort } = useChatStream()

// 自动滚动到底部
watch(messages, async () => {
    await nextTick()
    if (chatContainer.value) {
        chatContainer.value.scrollTop = chatContainer.value.scrollHeight
    }
}, { deep: true })

// 提交处理
const handleSubmit = () => {
    if (!input.value.trim() || isStreaming.value) return
    console.log(input.value)
    streamChat(messages, input.value)
    input.value = ''
}
</script>

<template>
    <div class="chat-container">
        <div ref="chatContainer" class="messages">
            <div v-for="msg in messages" :key="msg.id" :class="['message', msg.role]">
                <div class="role-badge">{{ msg.role === 'user' ? '你' : 'AI' }}</div>
                <div class="content">{{ msg.content }}</div>
            </div>
        </div>

        <form @submit.prevent="handleSubmit" class="input-area">
            <input v-model="input" :disabled="isStreaming" placeholder="输入消息..." />
            <button type="submit" :disabled="isStreaming">
                {{ isStreaming ? '生成中...' : '发送' }}
            </button>
            <button v-if="isStreaming" @click="abort" type="button" class="cancel-btn">
                停止
            </button>
        </form>

        <div v-if="error" class="error-message">
            {{ error.message }}
            <button @click="error = null">关闭</button>
        </div>
    </div>
</template>

<style scoped>
.chat-container {
    max-width: 800px;
    width: 800px;
    margin: 0 auto;
    height: 80vh;
    display: flex;
    flex-direction: column;
    text-align: left;
}

.messages {
    flex: 1;
    overflow-y: auto;
    padding: 1rem;
}

.message {
    margin: 1rem 0;
    padding: 1rem;
    border-radius: 8px;
    animation: fadeIn 0.3s ease-in;
}

.message.user {
    background: #f0f4ff;
    margin-left: 20%;
}

.message.assistant {
    background: #f5f5f5;
    margin-right: 20%;
}

@keyframes fadeIn {
    from {
        opacity: 0;
        transform: translateY(10px);
    }

    to {
        opacity: 1;
        transform: translateY(0);
    }
}

.input-area {
    padding: 1rem;
    display: flex;
    gap: 0.5rem;
    background: white;
    box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
}

input {
    flex: 1;
    padding: 0.8rem;
    border: 1px solid #ddd;
    border-radius: 4px;
}

button {
    padding: 0.8rem 1.5rem;
    background: #10b981;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
}

.cancel-btn {
    background: #ef4444;
}

.error-message {
    color: #ef4444;
    padding: 1rem;
    background: #fee2e2;
    margin: 1rem;
    border-radius: 4px;
}
</style>